package com.github.permissiondog.cancanpbackend;


import lombok.Getter;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class Database {
    private static final Database INSTANCE;

    static {
        try {
            INSTANCE = new Database();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Database getInstance() {
        return INSTANCE;
    }

    @Getter private final SqlSessionFactory sqlSessionFactory;

    private Database() throws IOException {
        String configPath = "com/github/permissiondog/cancanpbackend/resource/mybatis-config.xml";
        this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(configPath));
    }

    public SqlSession openSession() {
        return this.sqlSessionFactory.openSession(true);
    }
    public SqlSession openSession(boolean autoCommit) {
        return this.sqlSessionFactory.openSession(autoCommit);
    }

}
